package middlewares

import (
	"back/app/config"
	"back/app/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Request.Header.Get("Authorization")
		if tokenString == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"status":  "error",
				"message": "no-token-offered",
				"data":    nil,
			})
			c.Abort()
			return
		}

		jwtStringArray := strings.Split(tokenString, " ")
		jwtStringArrayLen := len(jwtStringArray)
		if jwtStringArrayLen == 1 {
			c.JSON(http.StatusUnauthorized, gin.H{
				"status":  "error",
				"message": "no-token-offered",
				"data":    nil,
			})
			c.Abort()
			return
		}

		jwt := utils.JWT{}
		userID, username, usertype, err := jwt.Parse(jwtStringArray[1], config.Config.Web.Secret)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"status":  "error",
				"message": err.Error(),
				"data":    nil,
			})
			c.Abort()
			return
		}

		c.Set("user_id", userID.(string))
		c.Set("user_name", username.(string))
		c.Set("type", usertype.(string))
		c.Next()
	}
}
